package cn.jetpiece.cloud.modular.router;

import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;

/**
 * nacos动态路由
 *
 * @author XuJZ
 */
@Slf4j
@Component
public class NacosDynamicRouteService implements ApplicationEventPublisherAware {
    private static final String SEP1 = "-";
    private static final String DOT = ".";
    private static final List<String> ROUTE_LIST = new ArrayList<>();
    @Resource
    private NacosConfigProperties properties;
    @Autowired
    private RouteDefinitionWriter routeDefinitionWriter;
    private ApplicationEventPublisher applicationEventPublisher;

    @PostConstruct
    public void dynamicRouteByNacosListener() {
        try {
            String name = properties.getName();
            String dataIdPrefix = properties.getPrefix();
            if (ObjectUtils.isEmpty(dataIdPrefix)) {
                dataIdPrefix = name;
            }
            if (ObjectUtils.isEmpty(dataIdPrefix)) {
                dataIdPrefix = properties.getEnvironment().getProperty("spring.application.name");
            }
            String serverAddr = properties.getServerAddr();
            String fileExtension = properties.getFileExtension();
            String nacosGroup = properties.getGroup();
            for (String profile : properties.getEnvironment().getActiveProfiles()) {
                String dataId = dataIdPrefix + SEP1 + profile + DOT + fileExtension;
                ConfigService configService = NacosFactory.createConfigService(serverAddr);
                configService.getConfig(dataId, nacosGroup, 5000);
                configService.addListener(dataId, nacosGroup, new Listener() {
                    @Override
                    public void receiveConfigInfo(String configInfo) {
                        clearRoute();
                        try {
                            List<RouteDefinition> gatewayRouteDefinitions = JSONObject.parseArray(configInfo, RouteDefinition.class);
                            for (RouteDefinition routeDefinition : gatewayRouteDefinitions) {
                                addRoute(routeDefinition);
                            }
                            publish();
                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        }
                    }

                    @Override
                    public Executor getExecutor() {
                        return null;
                    }
                });

            }
        } catch (NacosException e) {
            log.error(e.getErrMsg(), e);
        }
    }

    private void clearRoute() {
        for (String id : ROUTE_LIST) {
            this.routeDefinitionWriter.delete(Mono.just(id)).subscribe();
        }
        ROUTE_LIST.clear();
    }

    private void addRoute(RouteDefinition definition) {
        try {
            routeDefinitionWriter.save(Mono.just(definition)).subscribe();
            ROUTE_LIST.add(definition.getId());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    private void publish() {
        this.applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this.routeDefinitionWriter));
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }
}
